package com.nenglai.admin.handler;

import com.nenglai.common.response.*;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author kongdehui
 * @date 2021/04/20 21:15
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 默认欢迎页
     *
     * @return
     */
    @RequestMapping("/")
    public void index(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.getRequestDispatcher("index.html").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(Exception e) {
        return ResultGenerator.error(e.getMessage());
    }

    @ExceptionHandler(value = ValidateException.class)
    public Result<Map<String, String>> validateExceptionHandler(ValidateException e) {
        return ResultGenerator.error(ErrorCode.VALIDATOR_ERROR_CODE, e.getErrors());
    }

    @ExceptionHandler(value = ResponseException.class)
    public Result<String> responseExceptionHandler(ResponseException e) {
        ErrorCode errorCode = e.getErrorCode();
        return ResultGenerator.error(errorCode);
    }

    @ExceptionHandler(value = BindException.class)
    public Result<Map<String, String>> validationExceptionHandler(BindException e) {
        Map<String, String> map = new HashMap<>();
        if (e.getBindingResult().hasErrors()) {
            e.getBindingResult().getFieldErrors().forEach(v -> {
                map.put(v.getField(), v.getDefaultMessage());
            });
        }
        return ResultGenerator.error(ErrorCode.VALIDATOR_ERROR_CODE, map);
    }
}
